package com.yuandian.business.monitor.service.impl;


import com.yuandian.api.management.feign.RemoteAsynchronousDownloadService;
import com.yuandian.bpm.common.core.constant.SecurityConstants;
import com.yuandian.business.monitor.service.IDocumentExportService;
import com.yuandian.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Slf4j
//@Configuration
@Service
@RequiredArgsConstructor
public class DocumentExportImpl implements IDocumentExportService {

	private final RemoteAsynchronousDownloadService remoteAsynchronousDownloadService;
	/**
	 * 当前应用程序，启动目录
	 */
	private final String user_path = "user.dir";
	/**
	 * 文档生成存放路径名称
	 */
	private final String doc_path = "docs";
	/**
	 * 文档生成存放基础路径
	 */
	private final String basePath = System.getProperty(user_path) + File.separator + doc_path + File.separator;

	/**
	 * 该进程服务名称
	 */
	private String serviceCode;

	@Value("${server.servlet.context-path:BPM}")
	public void setServiceCode(String serviceCode) {
		if (serviceCode != null && !"".equals(serviceCode)) {
			this.serviceCode = serviceCode.substring(1, serviceCode.length());
		} else {
			throw new IllegalAccessError("该服务路径没有进行设置");
		}
	}


	@Override
	public void downloadDoc(String fileName, HttpServletResponse response) {
		File doc = null;
		// 1、检查文件名称合法性
		boolean isLegal = StringUtils.checkFileName(fileName);
		if (!isLegal) {
			throw new IllegalArgumentException("文件名不合法，请传入合法文件名称！" );
		}
		if (fileName != null && !"".equals(fileName)) {
			doc = new File(basePath + fileName);
			if (doc == null || (doc != null && !doc.exists())) {
				log.error("导出的文档路径不存在：文档名称：" + fileName);
				throw new IllegalArgumentException("导出的文档路径不存在!");
			}
		}
		try {
			// 清空response
			response.reset();
			ServletOutputStream out = response.getOutputStream();
			BufferedOutputStream bufferedWriter = new BufferedOutputStream(out);
			BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(basePath + fileName));
			// 临时缓冲区
			byte tmp[] = new byte[1024];
			int len = 0;
			while ((len = fileInputStream.read(tmp)) > 0) {
				bufferedWriter.write(tmp, 0, len);
			}

			// 设置response的Header
			response.addHeader("Content-Length", "" + doc.length());
			fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
			response.setContentType("application/vnd.ms-excel");

			// 循环将每次读入的至缓存的区域的，写出至输出流中
			bufferedWriter.flush();
			bufferedWriter.close();
			fileInputStream.close();
			//文件下载完成后,删除服务器缓存的文件

			doc.deleteOnExit();
			remoteAsynchronousDownloadService.deleteDocumentHandleInfoByFileName(fileName, SecurityConstants.FROM_IN);
		} catch (IOException e) {
			log.error("文档导出异常：文档名称：" + fileName, e);
			throw new IllegalArgumentException("文档导出异常：文档名称：" + fileName);
		}
	}

}
